package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 客户端
 */
public class Client {
    private Socket socket;
    public Client(){
        try {
            System.out.println("正在连接服务器...");
            /**
             * 实例化Socket对象，与远端计算机建立连接
             *  @host IP地址
             *  @port 端口号
             * */
            socket = new Socket("localhost",8080);//创建Socket对象，进行三次握手
            System.out.println("连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);

            Scanner input = new Scanner(System.in);
            System.out.println("请输入昵称");
            //要求：昵称为空或只有空格，则提示，并重输
            while(true){
                String nickname = input.nextLine();
                if(nickname.trim().isEmpty()){
                    System.out.println("输入为空，请重新输入");
                }else{
                    pw.println(nickname);
                    System.out.println("你好"+nickname+",欢迎进入群聊。");
                    break;
                }
            }


            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.setDaemon(true);
            t.start();


            while(true){
                String line = input.nextLine();
                if("exit".equalsIgnoreCase(line)){
                    break;
                }
                pw.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                socket.close();//进行四次挥手
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public class ServerHandler implements Runnable{
        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in,StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String messageFormServer;
                while((messageFormServer = br.readLine())!=null){
                    System.out.println(messageFormServer);
                }
            } catch (IOException e) {

            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
}
